import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';

const randomGradient = () => {
  const gradients = [
    'linear-gradient(135deg, #f87171 0%, #f472b6 100%)', // 红到粉
    'linear-gradient(135deg, #60a5fa 0%, #34d399 100%)', // 蓝到绿
    'linear-gradient(135deg, #facc15 0%, #fb923c 100%)', // 黄到橙
    'linear-gradient(135deg, #c084fc 0%, #818cf8 100%)', // 紫到靛
    'linear-gradient(135deg, #2dd4bf 0%, #4ade80 100%)', // 青到绿
  ];
  return gradients[Math.floor(Math.random() * gradients.length)];
};

const randomSpeed = () => Math.random() * 8 + 5; // 5s - 13s
const randomDelay = () => Math.random() * 3; // 0s - 3s
const randomGap = () => Math.random() * 20 + 10; // 10px - 30px 间距
const randomRotate = () => Math.random() * 6 - 3; // -3deg 到 3deg 微旋转
const randomFontSize = () => Math.random() * 4 + 22; // 12px - 16px

const ScrollingTags = ({ tags, maxVisible = 150 }) => {
  const [visibleTags, setVisibleTags] = useState([]);

  useEffect(() => {
    setVisibleTags(tags.slice(0, maxVisible));
  }, [tags, maxVisible]);

  return (
    <div className="relative w-full h-24 overflow-hidden">
      {visibleTags.map((tag, index) => {
        const speed = randomSpeed();
        const delay = randomDelay();
        const gap = randomGap();
        const gradient = randomGradient();
        const rotate = randomRotate();
        const fontSize = randomFontSize();

        return (
          <motion.div
            key={index}
            className="absolute px-2 py-1 rounded-full text-gray-900 font-medium" // 减少内边距
            style={{
              top: `${index * 30}px`, // 增加间距，避免重叠
              left: '100%',
              marginRight: `${gap}px`,
              backgroundImage: gradient, // 使用渐变背景
              boxShadow: '0 4px 15px rgba(0, 0, 0, 0.1)', // 柔和阴影
              border: '1px solid rgba(255, 255, 255, 0.5)', // 白色半透明边框
              opacity: 0.9, // 轻微透明度
              transform: `rotate(${rotate}deg)`, // 随机微旋转
              fontSize: `${fontSize}px`, // 随机字体大小
              minWidth: '100px', // 设置最小宽度，避免太短
              display: 'inline-block', // 让宽度自适应内容
              whiteSpace: 'nowrap', // 防止文字换行
            }}
            initial={{ x: '100%' }}
            animate={{ x: '-100%' }}
            transition={{ repeat: Infinity, duration: speed, ease: 'linear', delay }}
          >
            {tag}
          </motion.div>
        );
      })}
    </div>
  );
};

export default ScrollingTags;